<?php

namespace system\libs\validator;

/**
 * Form validation tool.
 *
 * Basic usage:
 * <code>
 *      $validator = new Validator();
 *      $validator->validate('name', $_POST['name'])->notNull()->alfaNumeric();
 *      $validator->validate('email', $_POST['email'])->notNull()->valid_email();
 *
 *      // array of errors contains all errors descriptions
 *      $errors = $validator->validateAll();
 *
 *      if($validator->hasErrors)  die('Errors');
 * </code>
 *
 * The output of Validator->validateAll() has following structure:
 * <code>
 *      errorsArray{
 *          nameArray{
 *              NotNull = 'fail',
 *              AlfaNumeric = 'fail'
 *          }
 *          emailArray{
 *              NotNull = 'fail',
 *              Email = 'fail'
 *          }
 *      }
 * </code>
 *
 * @see FormField
 * @package system\libs\validator
 * @author Pavel Egorov {@link mailto:pavel@egorov.ru pavel@egorov.ru}
 * @version $Revision: 63 $
 * @copyright Copyright (c) 2011, Pavel Egorov
 */

class Validator {

    private $formFieldsArray;
    private $errors;

    /**
     * Adds new validation context
     *
     * @param String $fieldName
     * @param String $fieldValue
     * @return Formfield Validation context
     */
    public function validate($fieldName, $fieldValue) {
        $this->formFieldsArray[$fieldName] = new FormField($fieldName, $fieldValue);
        return $this->formFieldsArray[$fieldName];
    }

    /**
     * Validate all {@link Formfield} contexts
     * 
     * @return array Array of errors that contains error descriptions
     */
    public function validateAll() {
        foreach ($this->formFieldsArray as $key => $field) {
            if (!$field->isValid()) {
                $this->errors[] = $field->getErrors();
            }
        }
        return $this->errors;
    }

    /**
     *
     * @return bool TRUE if no errors occurred FALSE otherwise
     */
    public function hasErrors(){
        return count($this->errors) > 0;
    }
}